# -*-coding:utf-8-*-

import json
import functools

from tornado.gen import coroutine

from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete
from utils.auth import authenticated
from handlers.base import BaseHandler


class PlatformDevicesHandler(BaseHandler):
    def __init__(self, application, request, **kwargs):
        super(PlatformDevicesHandler, self).__init__(application, request, **kwargs)
        self.delegate_name = 'devices'
        self.wait_id = None

    def check_permissions(self, permissions):
        # module_vendor 才有导入与删除权限
        # self.request.path
        return True

    def _get_device_ids_from_query(self):
        device_ids = self.get_argument('device_ids')
        return device_ids.split(',')

    @get(_path='/platform/api/devices')
    @authenticated
    @coroutine
    def platform_get_device_list(self):
        result = yield self.delegate_get_list(self.devices_dao, None, platform=True)
        self.respond_success(result)

    @get(_path='/platform/api/devices/{aspect}', _type=[str])
    @authenticated
    @coroutine
    def platform_get_device(self, aspect):
        if 'count' == aspect:
            result = yield self.delegate_get_list(self.devices_dao, None, get_count=True, platform=True)
        elif 'types' == aspect:
            result = ['WPM', 'BELL', 'IPC', 'ACS']
        else:
            device_id = aspect
            kwargs = self.query_arguments()
            guest_enable = self.app.guest_enable
            if guest_enable is not None and guest_enable:
                kwargs.update(guest_enable=guest_enable)
            kwargs.update(platform=True)
            filter_cond, projection = yield self.delegate_pre_get(self.delegate_name, **kwargs)
            filter_cond.update(device_id=device_id)
            result = yield self.devices_dao.find_one(filter_cond, projection)
            if result and 'owner_id' in result:
                projection = {'_id': 0, 'app_id': 0, 'password': 0}
                result['owner'] = yield self.users_dao.get_user_raw(self.app, user_id=result['owner_id'],
                                                                    projection=projection)
        self.respond_success(result)

    @post(_path='/platform/api/devices', _types=[dict],
          _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def platform_batch_create_device(self, request):
        device_ids = self._get_device_ids_from_query()
        result = yield self.devices_dao.platform_batch_create_device(self.user_id, device_ids, request)
        self.respond_success(result)

    @put(_path='/platform/api/devices', _types=[dict],
         _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def platform_batch_update_device(self, request):
        device_ids = self._get_device_ids_from_query()
        result = yield self.devices_dao.platform_batch_update_device(self.user_id, device_ids, request)
        if result and 'enabled' in request:
            payload = dict(enabled=request['enabled'])
            payload = json.dumps(payload)
            for device_id in device_ids:
                topic = 't/d/%s/n/enabled' % device_id
                self.mqtornado.publish(topic, payload)
        self.respond_success(result)

    @put(_path='/platform/api/devices/specifics', _types=[dict],
         _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def platform_batch_update_device_specifics(self, request):
        device_ids = self._get_device_ids_from_query()
        kwargs = dict(specifics=request, device_ids=device_ids)
        handle_update = functools.partial(self.devices_dao.platform_batch_update_device_specifics,
                                          self.user_id, device_ids)
        result = yield self.delegate_update(self.delegate_name, handle_update, dict(), **kwargs)
        self.respond_success(result)

    @delete(_path='/platform/api/devices')
    @authenticated
    @coroutine
    def platform_batch_delete_device(self):
        device_ids = self._get_device_ids_from_query()
        result = yield self.devices_dao.platform_batch_delete_device(self.user_id, device_ids)
        self.respond_success(result)
